This is nothing to do with deciding who gets to play Bill Gates in the film of his life (me! me!) but instead refers to a way we can force the compiler to regard a value as being of a particular type.

The C compiler is fairly liberal, in that it tends to perform conversions of types automatically without being asked. For example, you can use the types char and int together in the same expression and the compiler will automatically convert from one to the other. However, it is sometimes necessary to force the compiler to regard a variable in a particular way, and you use casting to do this.

It has to be said that the kind of programs we are going to write will not need this facility particularly, but programs on larger systems do, particularly if you start to use structures. You cast a value to a particular type by giving the name of the type enclosed in brackets before the value you want to cast.

An example of casting could be used if we want to work out a floating point value which is to be calculated by dividing one integer by another.

We have already seen that the compiler will use integer division (to save time and make the program smaller) if it sees that two integers are being divided. However, I can force it to regard the integers as floating point types by the use of casting:

int i, j ;
float x ;
x = i / j ; 
/* wrong with integer division */ x = (float) i / (float) j ;
/* gets the sum right */

Putting (float) in front of the variables forces the compiler to treat them as floating point and therefore floating point division will be used to work out the result for x.

You might use casting to let you put integers into characters, but you should beware of doing too much of this. Similar to the program on the right, when I put an integer (which has a wide range of values) into a character the number gets "chopped off".

If you are wondering where the strange value of 182 comes from it is the remainder you get left when you try to divide 950 by 256. The compiler may complain that you have done something potentially dangerous, but it will still try to run your program!